/* eslint-disable no-prototype-builtins */
/*
 * @Descripttion:
 * @version:
 * @Author: sueRimn
 * @Date: 2020-10-12 15:10:11
 * @LastEditors: sueRimn
 * @LastEditTime: 2020-11-24 10:55:36
 */
import axios from "axios";

import { Message } from "element-ui";
import util from "./utilsTools";

const message = msg => {
    Message.error(msg);
};

const instance = axios.create({
    timeout: 60000 // 请求超时
});

// 请求拦截器
instance.interceptors.request.use(
    config => {
        if (config.data) {
            if (config.data.hasOwnProperty("user_id")) {
                config.data.user_id = util.getDES(String(config.data.user_id));
            } else if (config.data.hasOwnProperty("userId")) {
                config.data.userId = util.getDES(String(config.data.userId));
            } else if (config.data.hasOwnProperty("tc_user_id")) {
                config.data.tc_user_id = util.getDES(
                    String(config.data.tc_user_id)
                );
            } else if (config.data.hasOwnProperty("student_id")) {
                config.data.student_id = util.getDES(
                    String(config.data.student_id)
                );
            } else if (config.data.hasOwnProperty("mechanism_id")) {
                config.data.mechanism_id = util.getDES(
                    String(config.data.mechanism_id)
                );
            } else if (config.data.hasOwnProperty("uids")) {
                //uids 是 用户id 字符串集合，需要先拆分为数组后逐个加密再转为字符串集合
                var uids = config.data.uids.split(","); //用户ID集合数组
                var uids_ary = []; //新的数组存储加密后ID集合数组
                uids.forEach((item, index) => {
                    uids_ary.push(util.getDES(String(uids[index]))); //加密
                });
                config.data.uids = uids_ary.join(","); //字符串集合
            }
        }
        return config;
    },
    error => Promise.error(error)
);

// 响应拦截器
instance.interceptors.response.use(
    // 请求成功
    res => Promise.resolve(res.data),
    // 请求失败
    error => {
        console.log("错误", error);
        const { response } = error;
        if (response) {
            return Promise.reject(response);
        } else {
            // 处理断网的情况
            message("网络错误");
        }
    }
);

export default instance;
